import 'package:flutter/material.dart';

class DemoInhertedPage extends StatefulWidget {
  DemoInhertedPage({Key? key}) : super(key: key);

  @override
  _DemoInhertedPageState createState() => _DemoInhertedPageState();
}

class _DemoInhertedPageState extends State<DemoInhertedPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('InheritedWidget'),
      ),
      body: InheritedCount(),
    );
  }
}

class InheritedCount extends StatefulWidget {
  @override
  _InheritedCountState createState() => _InheritedCountState();
}

class _InheritedCountState extends State {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        child: Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
      body: Center(
        child: InheritedState(
            count: _count,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [WidgetA(), WidgetB()],
            )),
      ),
    );
  }
}

class WidgetA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(InheritedState.of(context)?.count.toString() ?? '');
  }
}

class WidgetB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(
      InheritedState.of(context)?.count.toString() ?? '',
      style: TextStyle(color: Colors.green, fontSize: 50),
    );
  }
}

class InheritedState extends InheritedWidget {
  /// 构造方法
  InheritedState({Key? key, required this.count, required Widget child})
      : assert(count != null),
        super(key: key, child: child);

  /// 需要共享的数据
  final int count;

  /// 获取组件最近当前的InheritedWidget
  static InheritedState? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<InheritedState>();
  }

  /// 通知依赖该树共享数据的子widget
  @override
  bool updateShouldNotify(covariant InheritedState oldWidget) {
    return count != oldWidget.count;
  }
}
